<?php

namespace Module\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\Form\Element;
use Zend\Form\Form;

class IndexController extends AbstractActionController {

    protected $moduleTable;
    protected $moduleGroupTable;
    protected $controllersTable;
    protected $modulesUsersTable;
    protected $authService;

    protected function deleteDirectory($dir) {
        if (!file_exists($dir)) {
            return true;
        }

        if (!is_dir($dir) || is_link($dir)) {
            return unlink($dir);
        }

        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..')
                continue;
            if (!$this->deleteDirectory($dir . "/" . $item)) {
                chmod($dir . "/" . $item, 0777);
                if (!$this->deleteDirectory($dir . "/" . $item))
                    return false;
            };
        }
        return rmdir($dir);
    }

    public function getAuthService() {
        if (!$this->authService) {
            $this->authService = $this->getServiceLocator()->get('AuthService');
        }

        return $this->authService;
    }

    public function getModuleTable() {
        if (!$this->moduleTable) {
            $this->moduleTable = $this->getServiceLocator()->get('Module\Model\ModuleTable');
        }
        return $this->moduleTable;
    }

    public function getModuleGroupTable() {
        if (!$this->moduleGroupTable) {
            $this->moduleGroupTable = $this->getServiceLocator()->get('Module\Model\ModulesGroupsTable');
        }
        return $this->moduleGroupTable;
    }

    public function getControllerTable() {
        if (!$this->controllersTable) {
            $this->controllersTable = $this->getServiceLocator()->get('Module\Model\ControllersTable');
        }
        return $this->controllersTable;
    }

    public function getModulesUsersTable() {
        if (!$this->modulesUsersTable) {
            $this->modulesUsersTable = $this->getServiceLocator()->get('Module\Model\ModulesUsersTable');
        }
        return $this->modulesUsersTable;
    }

    public function indexAction() {
        if ($this->request->isXmlHttpRequest()) {
            $modules = $this->getModuleTable()->fetchAllForJson();
            return new JsonModel(array(
                'success' => 'true',
                'modules' => $modules
            ));
        } else {
            $matches = $this->getEvent()->getRouteMatch();
            $page = $matches->getParam('page', 1);

            $resultSet = $this->getModuleTable()->fetchAll();
            $resultSet->buffer();
            $resultSet->next();

            $paginator = new \Zend\Paginator\Paginator(new \Zend\Paginator\Adapter\Iterator($resultSet));

            $paginator->setCurrentPageNumber($page);
            $paginator->setItemCountPerPage(20);

            return array('moduleArray' => $paginator);
        }
    }

    public function uninstallAction() {
        $id = (int) $this->params()->fromQuery('id');

        $module = $this->getModuleTable()->getById($id);

        $this->getModuleTable()->remove($id);

        $src = ROOT_PATH . '/modules/' . $module['key_name'];

        $this->deleteDirectory($src);

        $extSrc = ROOT_PATH . '/../app/modules/' . $module['key_name'];

        $this->deleteDirectory($extSrc);

        $this->redirect()->toRoute('module/process', array('controller' => 'index', 'action' => 'index'));
    }

    public function changeGroupAction() {
        if ($this->request->isPost()) {
            $mid = $this->params()->fromPost('id');

            $group_id = $this->params()->fromPost('group_id');

            $this->getModuleTable()->getTableGateway()->update(array('module_group_id' => $group_id), array('mid' => $mid));

            $this->redirect()->toRoute('module/process');
        }

        $mid = (int) $this->params()->fromQuery('id');


        $hidden = new Element\Hidden('id');
        $hidden->setValue($mid);

        $resultSet = $this->getModuleGroupTable()->getAll();
        $values = array();
        foreach ($resultSet as $row) {
            $values[$row['module_group_id']] = $row['name'];
        }

        $select = new Element\Select('group_id');
        $select->setLabel('Choose group: ');
        $select->setValueOptions($values);

        $group_id = (int) $this->params()->fromQuery('group_id');
        $select->setValue($group_id);

        $submit = new Element\Submit('submit');
        $submit->setValue('Save change');

        $form = new Form('changegroupform');
        $form->setAttribute('accept-charset', 'utf-8');
        $form->setAttribute('method', 'POST');


        $form->add($hidden);
        $form->add($select);
        $form->add($submit);

        return array('form' => $form);
    }

    public function getGeneralModulesAction() {
        if ($this->request->isXmlHttpRequest()) {
            $modules = $this->getModuleTable()->getGeneralModulesForJson();

            return new JsonModel(array(
                'success' => 'true',
                'modules' => $modules
            ));
        } else {
            return array();
        }
    }

    public function getExtControllerAction() {
        if ($this->request->isXmlHttpRequest()) {
            $controllers = array();

            $modulesId = array();

            $genModules = $this->getModuleTable()->getGeneralModules();

            foreach ($genModules as $module) {
                $modulesId[] = $module['mid'];
            }

            if ($this->getAuthService()->hasIdentity()) {
                $userInfo = $this->getAuthService()->getIdentity();

                $uid = (int) $userInfo->id;

                $modulesUser = $this->getModulesUsersTable()->getModulesUser($uid);

                if (is_array($modulesUser)) {
                    foreach ($modulesUser as $module) {
                        $modulesId[] = $module['mid'];
                    }
                }
            }

            foreach ($modulesId as $mid) {
                $resultSet = $this->getControllerTable()->getById($mid);
                foreach ($resultSet as $row) {
                    $controllers[] = $row['controller_name'];
                }
            }

            return new JsonModel(array(
                'success' => 'true',
                'controllers' => $controllers
            ));
        } else {
            return array();
        }
    }

}